#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys
import os
sys.path.append(os.path.abspath('../..'))
import time
import datetime
import camfwlib

if __name__ == '__main__':
    path = './images/'

    cf = camfwlib.camfwClient('172.16.80.30', 15680, './camfw.log', camfwlib.DEBUG) 

    cam_list = cf.get_cameralist()
    cf.log(camfwlib.DEBUG, 'returned camera id list : ' + ' '.join(cam_list))

    print "=== start streaming ==="
    cf.start_movie_streaming('cam1')
    time.sleep(1)
    termfrom = datetime.datetime.today()
    time.sleep(1)
    termto = datetime.datetime.today()
    time.sleep(1)

    print "--- all ---"
    frames = cf.get_movie_imagelist('cam1')
    print frames
    
    print "--- last ---"
    frames = cf.get_movie_imagelist('cam1', 'last')
    print frames
    
    print "--- first ---"
    frames = cf.get_movie_imagelist('cam1', 'first')
    print frames
    
    print "--- range ---"
    tf_string = termfrom.strftime('%Y-%m-%dT%H:%M:%S.%fZ')
    tt_string = termto.strftime('%Y-%m-%dT%H:%M:%S.%fZ')
    frames = cf.get_movie_imagelist('cam1', [tf_string, tt_string])
    print frames
    
    print "--- get_imagedata & save ---"
    count = 0
    for frame in frames:
        framedata = cf.get_movie_imagedata(frame)
        if framedata:
            print len(framedata)
            fp = open(path + frame + '.jpg', 'w')
            fp.write(framedata)
            fp.close()
            count = count + 1

    print "total %d saved" % count

    cf.stop_movie_streaming('cam1')
    print "=== stop streaming ==="
